<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 头部警告区域 -->
      <el-alert :closable="false" title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon></el-alert>
      <el-row class="cat_opt">
        <el-col :span="8">
          <span class="cateTitle">选择商品分类</span>
          <!-- 商品分类级联选择器 -->
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="cascaderProps"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            class="cat_btn"
            type="primary"
            :disabled="isBtnDisable"
            @click="showAddParamsDialog"
          >添加参数</el-button>
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  type="primary"
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(scope.row,index)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-eidt"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            class="cat_btn"
            type="primary"
            :disabled="isBtnDisable"
            @click="showAddParamsDialog"
          >添加属性</el-button>
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  type="primary"
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(scope.row,index)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-eidt"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加动态参数和静态属性用的对话框 -->
    <el-dialog
      :title="'添加'+titlsText"
      :visible.sync="addParamsDialog"
      @close="addParamsDialogClose"
    >
      <el-form
        :model="addParamsForm"
        :rules="addParamsFormRules"
        ref="addParamsFormRef"
        label-width="100px"
      >
        <el-form-item :label="titlsText" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialog = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改动态参数静态属性用的对话框 -->
    <el-dialog
      :title="'修改'+titlsText"
      :visible.sync="editParamsDialog"
      @close="editParamsDialogClose"
    >
      <el-form
        :model="editParamsForm"
        :rules="edihtParamsFormRules"
        ref="editParamsFormRef"
        label-width="100px"
      >
        <el-form-item :label="titlsText" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialog = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      // 商品分类列表
      cateList: [],
      // 级联选择框的配置对象
      cascaderProps: {
        // 展开的方式
        expandTrigger: 'hover',
        // value用的是哪个属性
        value: 'cat_id',
        // 文本用的是哪个属性
        label: 'cat_name',
        // 子类用的是哪个属性
        children: 'children'

      },
      // 级联选择器选择的内容
      selectedKeys: [],
      // 选中的标签页,默认是第一个标签,many/only作为获取动态
      // 参数接口的参数，用名称来标识比较方便
      activeName: 'many',
      // 动态参数的数据
      manyTableData: [],
      // 静态属性的数据
      onlyTableData: [],
      // 添加参数对话框的状态控制
      addParamsDialog: false,
      // 添加参数的表单对象
      addParamsForm: {
        attr_name: '',
        attr_sel: '',
        attr_vals: ''
      },
      // 添加参数用到的验证规则
      addParamsFormRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      },
      // 修改参数对话框的状态控制
      editParamsDialog: false,
      // 修改参数的表单
      editParamsForm: {

      },
      // 编辑对话框的验证规则
      edihtParamsFormRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      },
      // 控制按钮与文本框的切换形式
      inputVisible: false,
      // 文本框中输入的内容
      inputValue: ''

    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status !== 200) return this.$message.error('获取分配列表失败')
      this.cateList = res.data
      //   console.log(this.cateList)
    },
    // 级联选择器选中后触发事件
    async handleChange () {
      if (this.selectedKeys.length !== 3) {
        // 如果选中的不是三级分类，将选中项置空
        this.selectedKeys = []
        this.manyTableData = []
        this.onlyTableData = []
      }
      this.getParamsData()
    },
    // 标签页的点击事件
    handleTabClick () {
      this.getParamsData()
    },
    // 获取参数的列表数据
    async getParamsData () {
      if (this.selectedKeys.length !== 3) {
        // 如果选中的不是三级分类，将选中项置空
        this.selectedKeys = []
        return this.$message.info('您选择的并非三级菜单哦')
      }
      //  当级联选择器通过验证后，发送请求获取级联选择器选择项的动态参数/静态属性
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } })

      if (res.meta.status !== 200) return this.$message.error('请求失败')
      // 遍历data中的每一个数据，将其中的attr_vals（字符串）转化为一个数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 给每条数据设置一个单独的属性用来存放标签文本的状态控制
        item.inputVisible = false
        // 给每条数据设置一个单独的属性用来存放数据绑定的变量
        item.inputValue = ''
      })

      // 如果要获取动态参数的数据
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 点击添加参数按钮唤醒对话框
    showAddParamsDialog () {
      this.addParamsDialog = true
    },
    // 当对话框关闭的时候
    addParamsDialogClose () {
      // 重置表的验证
      this.$refs.addParamsFormRef.resetFields()
    },
    // 点击对话框中的确定按钮
    addParams () {
      this.$refs.addParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        console.log(res)
        if (res.meta.status !== 201) { return this.$message.error('添加参数失败') }
        this.$message.success('添加参数成功')
        this.addParamsDialog = false
        this.getParamsData()
      })
    },
    // 点击编辑按钮
    async showEditDialog (attrId) {
      // 查询当前参数的信息
      this.editParamsDialog = true
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attrId}`, {
        params: {
          attr_sel: this.activeName
        }
      })
      if (res.meta.status !== 200) return this.$message.error('获取参数失败')
      // console.log(res)
      this.editParamsForm = res.data
    },
    // 编辑对话框关闭触发事件
    editParamsDialogClose () {
      // 重置修改的表单
      this.$refs.editParamsFormRef.resetFields()
    },
    // 点击编辑对话框中的确定按钮
    editParams () {
      this.$refs.editParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, {

          attr_name: this.editParamsForm.attr_name,
          attr_sel: this.activeName

        })
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('修改参数失败')
        this.getParamsData()
        this.editParamsDialog = false
      })
    },
    // 根据ID删除
    async removeParams (id) {
      const confirm = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(confirm)
      if (confirm !== 'confirm') return this.$message.info('取消了删除')
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getParamsData()
    },
    // 展开项标签中的文本框失去焦点或按下enter键触发
    async handleInputConfirm (row) {
      // 如果输入的只有空格，将inputvalue设置为空字符
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 如果没有return，说明输入了合法内容
      row.attr_vals.push(row.inputValue.trim())
      console.log(row.attr_vals)
      this.editAttrVals(row)
    },
    // 点击了tag中的新增按钮，切换成输入框
    showInput (row) {
      row.inputVisible = true
      // 让文本框自动获取焦点
      // $nextTick的作用就是当页面上元素被重新渲染之后才会执行回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 当标签关闭的时候
    handleClose (row, index) {
      row.attr_vals.splice(index, 1)
      this.editAttrVals(row)
    },
    // 当attr_vals删除或添加时
    async editAttrVals (row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('修改参数失败')
      this.$message.success('修改参数成功')
      console.log(row.attr_vals)
      row.inputValue = ''
      row.inputVisible = false
    }
  },
  computed: {
    // 根据selectedKeys判断按钮是否状态
    isBtnDisable () {
      //   如果按钮需要被禁用
      var isDisable = this.selectedKeys.length !== 3
      return isDisable
    },
    // 从selectedKeys中获取最后一项
    cateId () {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      } else {
        return null
      }
    },
    // 得出对话框的标题
    titlsText () {
      var title
      title = this.activeName === 'many' ? '动态属性' : '静态参数'
      return title
    }

  }

}
</script>
<style lang="less" scoped>
.cat_opt {
  margin: 15px;
}
.cat_btn {
  margin-bottom: 15px;
}
.cateTitle {
  margin-right: 15px;
}
.el-tag {
  margin: 5px;
}
.input-new-tag {
  width: 120px;
}
</style>
